package com.huiqiao.lesson4.utils;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 密码工具类 - 教学版（MD5 + 随机盐）
 * 可用于 MyBatis RBAC 权限系统示例
 */
public class PasswordUtils {

    private static final String ALGORITHM = "MD5";
    private static final int SALT_LENGTH = 8;

    /**
     * 生成随机盐
     */
    public static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[SALT_LENGTH];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    /**
     * 对明文密码加盐并加密
     * @param plainPassword 明文密码
     * @return 形如  salt:密文  的组合字符串
     */
    public static String encrypt(String plainPassword) {
        String salt = generateSalt();
        String hash = md5Hex(plainPassword + salt);
        return salt + ":" + hash;
    }

    /**
     * 验证密码是否匹配
     * @param plainPassword 明文密码
     * @param stored 密文（格式：salt:hash）
     */
    public static boolean verify(String plainPassword, String stored) {
        if (stored == null || !stored.contains(":")) {
            return false;
        }
        String[] parts = stored.split(":");
        String salt = parts[0];
        String hash = parts[1];
        String computed = md5Hex(plainPassword + salt);
        return computed.equals(hash);
    }

    /**
     * 执行 MD5 加密
     */
    private static String md5Hex(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance(ALGORITHM);
            byte[] digest = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5加密出错", e);
        }
    }

    // =================== 示例测试 ===================
    public static void main(String[] args) {
        String plain = "123456";
        String encrypted = encrypt(plain);
        System.out.println("原始密码：" + plain);
        System.out.println("存储密文：" + encrypted);
        System.out.println("验证通过？" + verify(plain, encrypted));
    }
}

